package org.gordonframework.site.transitions {
	import org.gordonframework.core.events.GProcessEvent;
	import org.gordonframework.core.tween.GTween;
	import org.gordonframework.site.transitions.GTransition;	

	/**
	 * @author sampet
	 */
	public class GCrossFade extends GTransition {

		private var duration:Number;
		private var tween:GTween;

		private var tweening:Boolean;

		public function GCrossFade(duration:Number = 0.5) {
			this.duration = duration;
		}

		override protected function hideView():void {
			if(tweening) {
				tween.removeEventListener( GProcessEvent.COMPLETE, tweenInCompleteHandler );				tween.addEventListener( GProcessEvent.COMPLETE, tweenOutCompleteHandler );
			} else {
				hideViewComplete();
			}
		}

		private function tweenOutCompleteHandler(event:GProcessEvent):void {
			tweening = false;
			if(oldView) {
				oldView.visible = false;
			}
			currentView.intro(durationMultiplier);
			hideViewComplete();
		}

		override protected function showView():void {
			
			tweening = true;
			
			if(oldView && container.getChildIndex( oldView ) > container.getChildIndex( currentView )) {
				currentView.alpha = 1;
				tween = new GTween( oldView, {alpha:0}, duration * durationMultiplier, oldView.outro(durationMultiplier) );
			} else {
				currentView.alpha = 0;
				if(oldView) {
				tween = new GTween( currentView, {alpha:1}, duration * durationMultiplier, oldView.outro(durationMultiplier) );
				}
				else {
					tween = new GTween( currentView, {alpha:1}, duration * durationMultiplier);
				}
			}
			
			currentView.visible = true; 
			
			tween.addEventListener( GProcessEvent.COMPLETE, tweenInCompleteHandler );
			tween.start( );		
		}

		private function tweenInCompleteHandler(event:GProcessEvent):void {
			tweening = false;
			if(oldView) {
				oldView.visible = false;
			}
			currentView.intro(durationMultiplier);
			showViewComplete();
		}
	}
}
